<template>
    <div>
        <div class="chat-title text-align-c">
             <img class="center-jt fl" src="../../assets/image/center/jtb.png" alt="" @click="$router.back(-1)">
            {{toName}}
        </div>
        <div class="clearfix chat-ul-box loadmoreBox" @click="showEmoji=false">
            <ul class="clearfix chat-ul" id="dialogue_box" :style="{minHeight:bodyHeight + 'px'}">
                <li class="clearfix" v-for="(item,index) in chatList" :key="index">
                    <img class="fl" v-if="item.wz == true" :src="$imgPath(item.sendUser.headImg)" alt="">
                    <img class="fr" v-else :src="$imgPath(item.sendUser.headImg)" alt="">
                    <div class="chat-div fl" v-if="item.wz == true">
                        <!-- <span class="chat-time" v-if="item.createTime != ''">{{$time(item.createTime)}}</span> -->
                        <span class="chat-nr fl left" v-html="handleMsg(item.descript)"></span>
                    </div>
                    <div class="chat-div fr" v-else>
                        <!-- <span class="chat-time text-align-r" v-if="item.createTime">{{$time(item.createTime)}}</span> -->
                        <!-- <span class="chat-nr fr" v-if="item.type == 200">{{item.descript}}</span> -->
                        <span class="chat-nr fr right" v-html="handleMsg(item.descript)"></span>
                    </div>
                </li>
            </ul>
        </div>
        <van-tabbar class="add-chat position-r">
            <div class="ib">
                <ul class="faces-ul" v-if="showEmoji">
                    <li v-for="(value,key) in emojiMap" :key="key" @click="clickFace(key)" class="webim-emoji-item">
                        <img :src="value" alt="emoj"/>
                    </li>
                </ul>
            </div>
            <div class="textarea-box"> 
                <span class="fl" @click="showEmoji = true">
                    <img src="../../assets/image/biaoqing.png" alt="">
                </span>
                <span class="fl position-r">
                    <img src="../../assets/image/fsPic.png" alt="">
                    <input type="file" ref="avatarInput2" id="file-Input" @change="picSong()">
                </span>
                <input type="text" class="fl" id="" v-model="chat_message" />
                <span class="fr add-other" @click="sendTextMsg()">发送</span>
            </div>
        </van-tabbar>
    </div>
</template>
<script>
import apiHttp from '../../api/index'
import { Toast } from 'vant'
import ee_1 from '../../assets/faces/ee_1.png'
import ee_2 from '../../assets/faces/ee_2.png'
import ee_3 from '../../assets/faces/ee_3.png'
import ee_4 from '../../assets/faces/ee_4.png'
import ee_5 from '../../assets/faces/ee_5.png'
import ee_6 from '../../assets/faces/ee_6.png'
import ee_7 from '../../assets/faces/ee_7.png'
import ee_8 from '../../assets/faces/ee_8.png'
import ee_9 from '../../assets/faces/ee_9.png'
import ee_10 from '../../assets/faces/ee_10.png'
import ee_11 from '../../assets/faces/ee_11.png'
import ee_12 from '../../assets/faces/ee_12.png'
import ee_13 from '../../assets/faces/ee_13.png'
import ee_14 from '../../assets/faces/ee_14.png'
import ee_15 from '../../assets/faces/ee_15.png'
import ee_16 from '../../assets/faces/ee_16.png'
import ee_17 from '../../assets/faces/ee_17.png'
import ee_18 from '../../assets/faces/ee_18.png'
import ee_19 from '../../assets/faces/ee_19.png'
import ee_20 from '../../assets/faces/ee_20.png'
import ee_21 from '../../assets/faces/ee_21.png'
import ee_22 from '../../assets/faces/ee_22.png'
import ee_23 from '../../assets/faces/ee_23.png'
import ee_24 from '../../assets/faces/ee_24.png'
import ee_25 from '../../assets/faces/ee_25.png'
import ee_26 from '../../assets/faces/ee_26.png'
import ee_27 from '../../assets/faces/ee_27.png'
import ee_28 from '../../assets/faces/ee_28.png'
import ee_29 from '../../assets/faces/ee_29.png'
import ee_30 from '../../assets/faces/ee_30.png'
import ee_31 from '../../assets/faces/ee_31.png'
import ee_32 from '../../assets/faces/ee_32.png'
import ee_33 from '../../assets/faces/ee_33.png'
import ee_34 from '../../assets/faces/ee_34.png'
import ee_35 from '../../assets/faces/ee_35.png'
export default {
    data(){
        return{
            toName:this.$route.query.to_username,
            toUserId:this.$route.query.to_userId,
            toCode:this.$route.query.to_code,
            toHeadImg:this.$route.query.to_headImg,
            chatList:[],
            userobj:{},
            bodyHeight:'',
            chat_message:'',
            showEmoji:false,
            emojiMap: {
                '[):]': ee_1,
                '[:D]': ee_2,
                '[;)]': ee_3,
                '[:-o]': ee_4,
                '[:p]': ee_5,
                '[(H)]': ee_6,
                '[:@]': ee_7,
                '[:s]': ee_8,
                '[:$]': ee_9,
                '[:(]': ee_10,
                '[:\'(]': ee_11,        
                '[:|]': ee_12,
                '[(a)]': ee_13,
                '[8o|]': ee_14,
                '[8-|]': ee_15,
                '[+o(]': ee_16,
                '[<o)]': ee_17,
                '[|-)]': ee_18,
                '[*-)]': ee_19,
                '[:-#]': ee_20,
                '[:-*]': ee_21,
                '[^o)]': ee_22,
                '[8-)]': ee_23,
                '[(|)]': ee_24,
                '[(u)]': ee_25,
                '[(S)]': ee_26,
                '[(*)]': ee_27,
                '[(#)]': ee_28,
                '[(R)]': ee_29,
                '[({)]': ee_30,
                '[(})]': ee_31,
                '[(k)]': ee_32,
                '[(F)]': ee_33,
                '[(W)]': ee_34,
                '[(D)]': ee_35
            },
        }
    },
    watch:{
        chatList(newVal,oldVal){
            this.msgScrollTop()
        }
    },
    mounted(){
        this.bodyHeight = document.body.clientHeight
        this.meIndexList()
        this.listByChat()
    },
    methods:{
        TalkDown () {
            let footer = document.getElementsByClassName('loadmoreBox')[0]
            footer.scrollTop = footer.scrollHeight
        },
        // 获取聊天的历史记录
        listByChat(){
            let parmes = {
                toUserId:this.toUserId
            }
            apiHttp.apiCenter.listByChat(parmes,resp=>{
                if(resp.code == 200){
                    for(let i in resp.data.content){
                        if(this.toUserId == resp.data.content[i].sendUser.id){
                            resp.data.content[i].wz = true
                        }else{
                            resp.data.content[i].wz = false
                        }
                        if(resp.data.content[i].sendUser.headImg==null || resp.data.content[i].sendUser.headImg==''){
                            resp.data.content[i].sendUser.headImg = '/user/head/defaultHeadImage.png';
                        }
                        this.chatList.unshift(resp.data.content[i])
                    }
                    this.TalkDown()
                }else{
                    Toast(resp.message)
                }
            })
        },
        //存储消息再本地服务器
        messageSend(userCode,title,descript,path,type){
            let params = {
                descript:descript,
				title:title,
				url:path,
				userCode:userCode,
				type:type
            }
            apiHttp.apiCenter.messageSend(params,resp=>{
                if(resp.code == 200){
                
                }else{
                    Toast(resp.message)
                }
            })
        },
        meIndexList(){      //获取自己的主页个人信息
            apiHttp.apiCenter.detail('',resp=>{                            
                this.uId = resp.id
                this.userobj = resp
                this.$imoption.user = resp.code
                this.openHx()                                                                                    
            })
        },
        // 开启环信
        openHx(){
            var self = this;
            self.$imconn.open(this.$imoption)
            self.$imconn.listen({
                onOpened(message){          //连接成功回调
                    console.log('用户已上线')
                },
                onTextMessage(message){    //收到文本消息
                    console.log(message)
                    let msg = {
                        descript:message.data,
                        wz:true,
                        createTime:'',
                        sendUser:{
                            headImg:self.toHeadImg
                        }
                    }
                    if(message.from == self.toCode){
                        self.chatList.push(msg)
                    }
                    
                },
                onPictureMessage(message) {
                    console.log(message)
                }
            })
        },
        // 发送消息
        sendTextMsg(){
            let self = this
            let id = this.$imconn.getUniqueId() 
            let msg = new WebIM.message('txt', id)
            msg.set({
                msg: self.chat_message,                  // 消息内容
                to: self.toCode,                          // 接收消息对象（用户id）
                roomType: false,
                success: function (id, serverMsgId) {
                    self.messageSend(self.toCode,"",self.chat_message,"",200)
                    let msg = {
                        descript:self.chat_message,
                        wz:false,
                        createTime:'',
                        type:200,
                        sendUser:{
                            headImg:self.userobj.headImg
                        }
                    }
                    self.chatList.push(msg)
                    self.chat_message = ''
                },
                fail: function(e){
                    console.log("Send private text error");
                }
            })
            msg.body.chatType = 'singleChat'
            this.$imconn.send(msg.body)
        },
        // 表情直接发送
        clickFace(key){
            let self = this
            let id = this.$imconn.getUniqueId() 
            let msg = new WebIM.message('txt', id)
            msg.set({
                msg: key,                  // 消息内容
                to: self.toCode,                          // 接收消息对象（用户id）
                roomType: false,
                success: function (id, serverMsgId) {
                    self.messageSend(self.toCode,"",key,"",202)
                    let msg = {
                        descript:key,
                        wz:false,
                        createTime:'',
                        type:202,
                        sendUser:{
                            headImg:self.userobj.headImg
                        }
                    }
                    self.showEmoji = !self.showEmoji
                    self.chatList.push(msg)
                },
                fail: function(e){
                    console.log("Send private text error");
                }
            })
            msg.body.chatType = 'singleChat'
            this.$imconn.send(msg.body)
        },
        // 表情过滤
        handleMsg (msg) {
            if (this.emojiMap[msg]) {
                return `<img src="${this.emojiMap[msg]}"/>`
            } else {
                return msg
            }
        },
        // 发送图片
        picSong(val){
            let self = this
            let id = self.$imconn.getUniqueId() 
            let msg = new WebIM.message('img', id)
            let input = document.getElementById('file-Input')
            let file = WebIM.utils.getFileUrl(input)
            let allowType = {
                'jpg': true,
                'gif': true,
                'png': true,
                'bmp': true
            }
            if(file.filetype.toLowerCase() in allowType){
                msg.set({
                    ext:{},
                    to: self.toCode,                          // 接收消息对象（用户id）
                    roomType: false,
                    apiUrl: self.$imoption.apiUrl,
                    file: file,
                    chatType:'singleChat',
                    roomType: false,
                    onFileUploadError: function (e) {      // 消息上传失败
                        console.log('失败');
                    },
                    onFileUploadComplete: function (e) {   // 消息上传成功
                        console.log('上传成功');
                    },
                    success: function (data) {                // 消息发送成功
                        let fd = new FormData()
                        fd.append('model','user/chat')
                        if (self.$refs.avatarInput2.files.length !== 0) {
                            fd.append('file', self.$refs.avatarInput2.files[0])
                        }
                        apiHttp.apiCenter.uploadImg(fd,resp=>{
                            if(resp.code = 200){
                                let msg = {
                                    descript:`<img src="${self.$imgPath(resp.data.url)}">`,
                                    wz:false,
                                    createTime:'',
                                    type:202,
                                    sendUser:{
                                        headImg:self.userobj.headImg
                                    }
                                }
                                self.chatList.push(msg)
                                self.messageSend(self.toCode,"",`<img src="${self.$imgPath(resp.data.url)}">`,"",202)
                                self.scrollTopDiv()
                            }
                        })
                    },
                    flashUpload: WebIM.flashUpload
                })
                self.$imconn.send(msg.body)
            }
        },
        // 滚动条到底部
        msgScrollTop(){
            this.$nextTick(function(){
                let div = document.getElementById('dialogue_box');
                div.scrollTop = div.scrollHeight
            })
        }
    },
    // updated:function(){
    //     this.$nextTick(function(){
    //         var div = document.getElementById('dialogue_box');
    //         div.scrollTop = div.scrollHeight;
    //     })
    // }
}
</script>

<style scoped>
.left:after {
    border-right-color: #D84E4D;
    top: 50%;
    right: 100%;
    margin-top: -9px;
}
.right:after {
    border-left-color: #D84E4D;
    left: 100%;
    top: 50%;
    margin-top: -7px;
}
.chat-title{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 1.5rem;
    font-size: .7rem;
    line-height: 1.5rem;
    border-bottom: solid 1px #ccc;
    background-color: #333;
    color:#fff;
}
.add-chat{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    border-top: solid 1px #ccc;
    height: 1.5rem;
}
.add-chat span{
    height: 1.5rem;
    line-height: 1.5rem;
    display: inline-block;
    font-size: .6rem;
    padding-right: .8rem;
}
.add-other{
    padding-left: .8rem;
    padding-right: 0 !important;
}
.add-chat input{
    width: calc(100% - 5rem - 1.2rem);
    height: 1.4rem;
    border-top:none;
    border-left:none;
    border-right:none;
    border-bottom: solid 1px #ccc;
    display: block;
}
.textarea-box{
    width: calc(100% - 1.2rem);
    height: 1.5rem;
    padding: 0;
    margin: 0;
}
.chat-ul-box{
    width: 100%;
    background-color: #f8f8f8;
}
.textarea-box span img{
    width: 1.1rem;
}
.chat-ul{
    width: calc(100% - 1.2rem);
    padding: 2rem .6rem 1rem .6rem;
}
.chat-ul li{
    min-height: 1.5rem;
    width: 100%;
    font-size: .6rem;
    padding-top: .5rem;
}
.chat-ul li img{
    width: 1.5rem;
    height: 1.5rem;
    border-radius: 50%;
}
.chat-div{
    width: calc(100% - 3rem);
    min-height: 1.5rem;
    margin-left: .5rem;
    margin-right: .5rem;
}
.chat-nr{
    min-height: 1rem;
    background-color: #fff;
    border-radius: .2rem;
    padding: .1rem .5rem;
    line-height: 1rem;
    border: .04rem solid #eee;
}
.chat-time{
    display: block;
    height: .8rem;
    line-height: .8rem;
    font-size: .4rem;
    width: 100%;
}
.ib{
    width: calc(100% - 1.2rem);
    height: auto;
    position: absolute;
    left: 0;
    bottom:2rem;
    padding: .3rem .6rem;
    border-radius: .2rem;
    background-color: #fff;
}
.faces-ul{
    width: calc(100% - 1.2rem);
    text-align: justify;
}
.faces-ul li{
    width: 1rem;
    display: inline-block;
}
#file-Input{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    opacity: 0;
    font-size: 0;
}
.center-jt{
    position: absolute;
    left: .6rem;
    top: .3rem;
}
</style>

